const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    brandShowed: false,
    brandVal: "",
    selectBrandName: "",
    selectPlateName: "",
    fieldsList: null,
    brandList: null,
    plateList: null,
    searchList:null,
    positionList: null,
    values:{
      paint: true,
      glass: true,
      wiper: true,
      carlight: true,
      tire: true,
      dashboard: true,
      electricity: true,
      washingwater: true,
      jack: true,
      charge: true,
      tripod: true,
      certificate: true,
      aircondition: true,
      sound: true,
      surface: true,
      interior: true
    },
    photos: {
      paint: [],
      glass: [],
      wiper: [],
      carlight: [],
      tire: [],
      dashboard: [],
      electricity:[],
      washingwater: [],
      jack: [],
      charge: [],
      tripod: [],
      certificate: [],
      aircondition: [],
      sound: [],
      surface: [],
      interior: []
    },
    _photos: {
      paint: [],
      glass: [],
      wiper: [],
      carlight: [],
      tire: [],
      dashboard: [],
      electricity: [],
      washingwater: [],
      jack: [],
      charge: [],
      tripod: [],
      certificate: [],
      aircondition: [],
      sound: [],
      surface: [],
      interior: []
    },
    remark:{
      paint: '',
      glass: '',
      wiper: '',
      carlight: '',
      tire: '',
      dashboard: '',
      electricity: '',
      washingwater: '',
      jack: '',
      charge: '',
      tripod: '',
      certificate: '',
      aircondition: '',
      sound: '',
      surface: '',
      interior: ''
    },     
    inspection: {
      car_status: true,
      carbrand_id:0,
      carplate_id:0,
      carposition_id:0,
      car_photo:'',
    },
    positionIndex: 0,
    inspection_car_photo:[]
    //carStatusAll: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    var that = this;
    var inspection = this.data.inspection
    var dataUrl = ""    
    var inspectionStorage=false;
    var positionIndex = 0
    var selectPlateName = ""
    var selectBrandName = ""

    var values = this.data.values
    var photos = this.data.photos
    var remark = this.data.remark

    
    
    if (options.id>0){
      that.setData({
        id: options.id
      })
      inspectionStorage = wx.getStorageSync('inspectionData.' + options.id)
      if (!inspectionStorage) {
        dataUrl = app.globalData.domain + "/api/inspection/edit/" + options.id;
      } else {
        dataUrl = app.globalData.domain + "/api/inspection/edit"
      }
    }else{
      dataUrl = app.globalData.domain + "/api/inspection/edit"
      
    }
   
    wx.request({
      url: dataUrl,
      data: {
        token: app.globalData.loginUserInfo.token
      },
      success: function (res) {
        console.log(res.data.data)
        if (res.data.data.inspection){
          inspectionStorage = res.data.data.inspection
          wx.setStorageSync("inspectionData." + options.id, res.data.data.inspection)
        }
        if (inspectionStorage){        
          inspection.car_photo = inspectionStorage.car_photo          
          inspection.car_status = inspectionStorage.car_status == 0 ? false : true
          inspection.carbrand_id = inspectionStorage.carbrand_id
          inspection.carplate_id = inspectionStorage.carplate_id
          inspection.carposition_id = inspectionStorage.carposition_id
                
          selectPlateName = inspectionStorage.plate
          selectBrandName = inspectionStorage.brand

          for (var a = 0; a < res.data.data.positionList.length; a++){
            if (res.data.data.positionList[a].id == inspectionStorage.carposition_id){              
              positionIndex = a;
            }
          }
          //console.log(photos);
          for (var c = 0; c < res.data.data.fields.length; c++) {
            //console.log(inspectionStorage.data)
            remark[res.data.data.fields[c].fieldname] = inspectionStorage.data[res.data.data.fields[c].fieldname].remark
            values[res.data.data.fields[c].fieldname] = inspectionStorage.data[res.data.data.fields[c].fieldname].fieldvalue == "1" ? true : false
            photos[res.data.data.fields[c].fieldname] = inspectionStorage.data[res.data.data.fields[c].fieldname].photo == null ? [] : inspectionStorage.data[res.data.data.fields[c].fieldname].photo
          }
          //console.log(photos);
        }else{
          inspection.carposition_id = res.data.data.positionList[0].id
          inspection.car_photo = []
        }
        
        that.setData({
          fieldsList: res.data.data.fields,
          brandList: res.data.data.brandList,
          plateList: res.data.data.plateList,
          positionList: res.data.data.positionList,
          inspection: inspection,
          inspection_car_photo: inspectionStorage.car_photo ? inspectionStorage.car_photo : [],
          positionIndex: positionIndex,
          selectPlateName: inspectionStorage.plate,
          selectBrandName: inspectionStorage.brand,
          remark: remark,
          values: values,
          photos: photos
        });
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  formSubmit: function (e) {
    var parameters = e.detail.value
    //console.log(this.data.inspection)
    for (var obj in this.data.inspection){
      if (this.data.inspection[obj] === 0){
        wx.showToast({
          title: '数据填写不完整数据填写不完整',
          image: '/pages/images/a2.png',
          duration: 3000
        });
        return false
      }
    }
    parameters.inspection = this.data.inspection
    parameters.inspection.car_photo = parameters.inspection.car_photo.join(',')
    parameters.values = this.data.values
    parameters.photos = this.data.photos
    //console.log(this.data.photos)
    if(this.data.id>0){
      parameters.id = this.data.id
    }

    wx.request({
      url: app.globalData.domain + "/api/inspection/store?token=" + app.globalData.loginUserInfo.token,
      data: parameters,
      method: 'post',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.status_code == 0){
          wx.reLaunch({
            url: '/pages/inspection/list/list',
          })
        }else{
          return ;
        }
      }
    })
  },
  removeCarImage: function(e){
    var inspection_car_photo = this.data.inspection_car_photo
    var inspection = this.data.inspection;
    inspection_car_photo.splice(e.currentTarget.dataset.index, 1)
    inspection.car_photo.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      inspection: inspection,
      inspection_car_photo: inspection_car_photo
    });
  },
  chooseCarImage: function(e){
    var that = this
    var inspection_car_photo = this.data.inspection_car_photo
    var inspection = this.data.inspection
    console.log(this.data);
    if (inspection.car_photo.length<4){
      wx.chooseImage({
        count: 1,
        sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          var tempFilePaths = res.tempFilePaths        
          wx.uploadFile({
            url: app.globalData.domain + "/api/inspection/upload?token=" + app.globalData.loginUserInfo.token,
            filePath: tempFilePaths[0],
            name: 'file',
            success: function (res) {              
              inspection_car_photo = inspection_car_photo.concat(tempFilePaths[0])
              inspection.car_photo = inspection.car_photo.concat(res.data)
              that.setData({
                inspection: inspection,
                inspection_car_photo: inspection_car_photo
              });
            }
          })
        }
      })
    }
  },
  chooseImage: function (e) {
    var that = this;    
    var photo_name = e.currentTarget.dataset.name;
    var photos = that.data.photos
    var values = that.data.values
    var inspection = this.data.inspection
    wx.chooseImage({
      count: 4,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //console.log(res)
       
        photos[photo_name] = []
        
        var tempFilePaths = res.tempFilePaths
        var photo_count = tempFilePaths.length >= 4 ? 4 : tempFilePaths.length
        for( var i = 0; i<photo_count; i++){
          wx.uploadFile({
            url: app.globalData.domain + "/api/inspection/upload?token=" + app.globalData.loginUserInfo.token,
            filePath: tempFilePaths[i],
            name: 'file',
            success: function (res) {           
              photos[photo_name] = photos[photo_name].concat(res.data)              
              values[photo_name] = false
              inspection.car_status=false
              that.setData({
                photos: photos,
                inspection: inspection,
                values: values
              });
            }
          })
        }
      }
    })
  },
  deleteImage: function (e) {
    var photo_name = e.currentTarget.dataset.name;
    var photos = this.data.photos
    console.log(photo_name)
    console.log(photos[photo_name])
    photos[photo_name] = []
    this.setData({
      photos: photos,      
    });
  },
  bindPositionChange: function(e){
    var inspectionX = this.data.inspection
    inspectionX.carposition_id = this.data.positionList[e.detail.value].id
    this.setData({
      positionIndex: e.detail.value,
      inspection: inspectionX
    });
  },
 
  carStatusChange: function(e){
    var data = this.data.values;
    for(var name in this.data.values){
      data[name] = !!e.detail.value
    }
    this.setData({
      values: data
    });
  },
  carDataStatusChange: function(e){
    var data = this.data.values;
    var car_status = true
    data[e.currentTarget.dataset.name] = !!e.detail.value

    for (var name in data) {
      if (!this.data.values[name]){
        car_status = false
      }      
    }    
    var inspection = this.data.inspection
    inspection.car_status = car_status
    this.setData({
      values: data,
      inspection: inspection
    });
  },
  

  showInput: function () {
    this.setData({
      brandShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      brandVal: "",
      brandShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      brandVal: ""
    });
  },
  inputTyping: function (e) {
    var searchList = [];
    for (var i=0; i<this.data.plateList.length; i++){      
      if (this.data.plateList[i].name.indexOf(e.detail.value)>=0){
        searchList.push(this.data.plateList[i]);
      }
    }
    this.setData({
      brandVal: e.detail.value,
      searchList: searchList
    });
  },
  selectValue: function(e){
    var inspection = this.data.inspection
    inspection.carbrand_id = e.currentTarget.dataset.brand_id
    inspection.carplate_id = e.currentTarget.dataset.plate_id
    this.setData({
      selectBrandName: e.currentTarget.dataset.brand_name,
      selectPlateName: e.currentTarget.dataset.plate_name,
      inspection: inspection,
      brandVal: ""
    });
    console.log(this.data.inspection)
  },
  
})
